import { Ref } from 'vue'
import { IStoreGoodsDetail, IStoreProductRow } from "@/api/modules/pointsMall";
import { request, post } from "@/utils/request";
import ApiResult from "@/api/base/ApiResult";
import { useGetCurrencyType } from "@/views/pointsMall/compositions/useGetCurrencyType";

/**
 * 获取商家商品详情，并对数据结构进行一定的初始化
 */
export function useGetSubmitStoreDetail() {
  const route = useRoute()
  const { id } = route.query

  const form = reactive<IStoreGoodsDetail>({} as any)
  const productOptions = ref<IStoreProductRow[]>([])
  const initialDetailText = ref('')

  const getDetail = async (url = 'merchant/member/goods/getStoreGoodsDetail', params = { id }) => {
    const rs: ApiResult<IStoreGoodsDetail> = await request(url, params)
    if (rs.code === 200) {
      if (rs.payload) {
        // 初始化form表单
        Object.keys(rs.payload).forEach(key => {
          form[key] = rs.payload?.[key]
        })

        // 初始化规格选项
        productOptions.value = rs.payload.products.map(item => ({
          ...item,
          thumbnailUrl: item.thumbnailUrl ?? '', // upload组件
          payOfCurrencyCount: 0,
          payPrice: item.payPrice / 100, // 后端存储单位为分
        }))
        // 初始化规格列表
        form.products = []
        // 初始化富文本编辑器初始值
        initialDetailText.value = rs.payload.detailText ?? ''
      }
    }
  }

  // const isEmpty = (val: any) => {
  //   return val === null || val === undefined || val === ''
  // }

  const formatData = () => {
    const _form = JSON.parse(JSON.stringify({ ...form })) as unknown as IStoreGoodsDetail

    _form.storeGoodsId = form.id
    _form.stock = form.products.reduce((total, current) => total + current.stock, 0)
    _form.products.forEach((product) => {
      product.payPrice = parseInt((product.payPrice * 100).toFixed(2).slice(0, -3)) // 后端接收的单位为分
    })

    return _form
  }

  return {
    form,
    productOptions,
    initialDetailText,
    formatData,
    getDetail,
  }
}
